package com.mingtu.jgspatrol.fragment;

import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.text.style.RelativeSizeSpan;
import android.text.style.StyleSpan;
import android.view.View;
import android.widget.RadioGroup;

import androidx.annotation.RequiresApi;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.github.mikephil.charting.animation.Easing;
import com.github.mikephil.charting.components.Legend;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.data.PieData;
import com.github.mikephil.charting.data.PieDataSet;
import com.github.mikephil.charting.data.PieEntry;
import com.github.mikephil.charting.formatter.PercentFormatter;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.IDataSet;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.github.mikephil.charting.utils.MPPointF;
import com.google.android.flexbox.AlignItems;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.google.gson.Gson;
import com.hjq.gson.factory.GsonFactory;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.mingtu.common.base.BaseBindingFragment;
import com.mingtu.common.callback.StringDialogCallback;
import com.mingtu.common.viewpager.LazyViewPager.LazyFragmentPagerAdapter;
import com.mingtu.jgspatrol.R;
import com.mingtu.jgspatrol.adapter.PiechartValueAdapter;
import com.mingtu.jgspatrol.bean.ReportTrendBean;
import com.mingtu.jgspatrol.bean.TagBean;
import com.mingtu.jgspatrol.databinding.FragmentReportDataBinding;
import com.mingtu.jgspatrol.utils.MyConstant;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class ReportDataFragment extends BaseBindingFragment<FragmentReportDataBinding> implements LazyFragmentPagerAdapter.Laziable {
    private String[] dateArray = {"year", "month"};
    private String dataStr = dateArray[0];
    private PiechartValueAdapter piechartValueAdapter;

    public static ReportDataFragment getInstance() {
        ReportDataFragment ef = new ReportDataFragment();
        return ef;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_report_data;
    }

    @Override
    protected void initData() {
        binding.radioGroup1.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                //本年  本月 本周
                switch (checkedId) {
                    case R.id.rb_but11:
                        dataStr = dateArray[0];
                        break;
                    case R.id.rb_but12:
                        dataStr = dateArray[1];
                        break;
                }
                getReportToatal();
            }
        });

        FlexboxLayoutManager flm1 = new FlexboxLayoutManager(getActivity());
        flm1.setFlexWrap(FlexWrap.WRAP);
        flm1.setFlexDirection(FlexDirection.ROW);
        flm1.setAlignItems(AlignItems.STRETCH);
        flm1.setJustifyContent(JustifyContent.FLEX_START);
        binding.recycler.setLayoutManager(flm1);

        piechartValueAdapter = new PiechartValueAdapter(context);
        binding.recycler.setAdapter(piechartValueAdapter);
    }

    @Override
    protected void initView() {
 
    }

    @Override
    protected void getData() {
        getReportToatal();
        getReportTag();
        getReportTrend();
    }


    /**
     * 上报总数据情况
     */
    private void getReportToatal() {
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("type", dataStr);
        String str = GsonUtils.toJson(hashMap);
        OkGo.<String>post(MyConstant.POST_REPORT_STA_TOATAL3)
                .tag(this)
                .upJson(str)
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            //{"msg":"success","code":0,"data":{"total":6,"exceptionNum":0,"normalNum":2}}
                            try {
                                JSONObject jsonObject = JSON.parseObject(result);
                                JSONObject dataObject = jsonObject.getJSONObject("data");
                                if (dataObject != null) {
                                    String type1 = dataObject.getString("normalNum");
                                    String type2 = dataObject.getString("exceptionNum");
                                    String type3 = dataObject.getString("total");

                                    if (!StringUtils.isEmpty(type1)) {
                                        binding.tvTotalCount1.setText(type1 + "");
                                    }
                                    if (!StringUtils.isEmpty(type2)) {
                                        binding.tvTotalCount2.setText(type2 + "");
                                    }

                                    if (!StringUtils.isEmpty(type3)) {
                                        binding.tvTotalCount3.setText(type3 + "");
                                    }

                                } else {
                                    binding.tvTotalCount1.setText("0");
                                    binding.tvTotalCount2.setText("0");
                                    binding.tvTotalCount3.setText("0");
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }
                    }
                });
    }


    /**
     * 上报总数据情况
     */
    private void getReportTag() {
        OkGo.<String>post(MyConstant.POST_REPORT_STA_TAG)
                .tag(this)
                .upJson("")
                .execute(new StringDialogCallback(getActivity()) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            Gson gson = GsonFactory.getSingletonGson();
                            TagBean tagBean = new TagBean();
                            tagBean = gson.fromJson(result, TagBean.class);
                            List<TagBean.ListBean> listBeans = tagBean.getList();

                            binding.layoutPieChart.setVisibility(View.GONE);
                            binding.emptyLayoutPie.setIsShowView(true);
                            if (listBeans != null) {
                                if (listBeans.size() > 0) {
                                    if (listBeans.size() <= 25) {
                                        binding.layoutPieChart.setVisibility(View.VISIBLE);
                                        binding.emptyLayoutPie.setIsShowView(false);
                                        ArrayList<PieEntry> entries = new ArrayList<>();
                                        ArrayList<Integer> colors = new ArrayList<>();
                                        for (int i = 0; i < listBeans.size(); i++) {
                                            int count = listBeans.get(i).getCount();
                                            entries.add(new PieEntry((float) count, count + ""));//已完成
                                        }
                                        for (int c : ColorTemplate.VORDIPLOM_COLORS)
                                            colors.add(c);

                                        for (int c : ColorTemplate.JOYFUL_COLORS)
                                            colors.add(c);

                                        for (int c : ColorTemplate.COLORFUL_COLORS)
                                            colors.add(c);

                                        for (int c : ColorTemplate.LIBERTY_COLORS)
                                            colors.add(c);

                                        for (int c : ColorTemplate.PASTEL_COLORS)
                                            colors.add(c);

                                        initPieChart(entries, colors);
                                        piechartValueAdapter.setColors(colors);
                                        piechartValueAdapter.replaceData(listBeans);
                                    } else {
                                        ToastUtils.showLong("类型太多了哦~");
                                    }

                                }
                            }
                        }
                    }
                });
    }


    /**
     * 上报趋势
     */
    private void getReportTrend() {
        OkGo.<String>post(MyConstant.POST_REPORT_STA_TREND)
                .tag(this)
                .upJson("")
                .execute(new StringDialogCallback(getActivity()) {
                    @RequiresApi(api = Build.VERSION_CODES.O)
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();
                        if (!StringUtils.isEmpty(result)) {
                            Gson gson = GsonFactory.getSingletonGson();
                            ReportTrendBean reportTrendBean = new ReportTrendBean();
                            reportTrendBean = gson.fromJson(result, ReportTrendBean.class);
                            List<ReportTrendBean.EventNumBean> eventNumBeans = reportTrendBean.getEventNum();

                            binding.layoutLineChart.setVisibility(View.GONE);
                            binding.emptyLayoutLine.setIsShowView(true);

                            if (eventNumBeans != null) {
                                if (eventNumBeans.size() > 0) {
                                    binding.layoutLineChart.setVisibility(View.VISIBLE);
                                    binding.emptyLayoutLine.setIsShowView(false);
                                    initLineChartData(eventNumBeans);
                                }
                            }

                        }
                    }
                });
    }

    /**
     * 饼状图
     */
    private void initPieChart(ArrayList<PieEntry> entries, ArrayList<Integer> colors) {
        binding.pieChart.setUsePercentValues(true);
        binding.pieChart.getDescription().setEnabled(false);
        binding.pieChart.setExtraOffsets(0, 0, 0, 0);

        binding.pieChart.setDragDecelerationFrictionCoef(0.95f);

//        binding.pieChart.setCenterTextTypeface(tfLight);
        binding.pieChart.setDrawCenterText(false);
        binding.pieChart.setDrawHoleEnabled(true);
        binding.pieChart.setHoleColor(Color.WHITE);

        binding.pieChart.setTransparentCircleColor(Color.WHITE);
        binding.pieChart.setTransparentCircleAlpha(110);

        binding.pieChart.setHoleRadius(58f);
        binding.pieChart.setTransparentCircleRadius(61f);


        binding.pieChart.setRotationAngle(0);
        // enable rotation of the chart by touch
        binding.pieChart.setRotationEnabled(true);
        binding.pieChart.setHighlightPerTapEnabled(true);

        // chart.setUnit(" €");
        // chart.setDrawUnitsInChart(true);

        // add a selection listener
//        chart.setOnChartValueSelectedListener(this);


        binding.pieChart.animateY(1400, Easing.EaseInOutQuad);

        Legend legend = binding.pieChart.getLegend();
        legend.setEnabled(false); //是否显示图例
        // entry label styling
        binding.pieChart.setEntryLabelColor(Color.WHITE);
//        chart.setEntryLabelTypeface(tfRegular);
        binding.pieChart.setEntryLabelTextSize(12f);
        binding.pieChart.setDrawEntryLabels(true); //是否显示label

        PieDataSet dataSet = new PieDataSet(entries, null);
        dataSet.setSliceSpace(3f);
        dataSet.setIconsOffset(new MPPointF(0, 40));
        dataSet.setSelectionShift(5f);

        // 颜色

        dataSet.setColors(colors);


        PieData data = new PieData(dataSet);
        data.setValueFormatter(new PercentFormatter());
        data.setValueTextSize(11f);
        data.setValueTextColor(Color.WHITE);
//        data.setValueTypeface(tfLight);
        binding.pieChart.setData(data);

        // undo all highlights
        binding.pieChart.highlightValues(null);

        //隐藏数值 Y
        for (IDataSet<?> set : binding.pieChart.getData().getDataSets())
            set.setDrawValues(false);

        binding.pieChart.invalidate();


    }

    private SpannableString generateCenterSpannableText(String rate) {

        SpannableString s = new SpannableString("完成率\n" + rate);
        s.setSpan(new RelativeSizeSpan(1f), 0, s.length(), 0);
        s.setSpan(new StyleSpan(Typeface.BOLD), 0, s.length(), 0);
        s.setSpan(new ForegroundColorSpan(getResources().getColor(R.color.text_color333)), 0, s.length(), 0);

        return s;
    }


    public void initLineChartData(List<ReportTrendBean.EventNumBean> taskNumBeans) {
        int xLableCount = taskNumBeans.size();
        binding.lineChart.getDescription().setEnabled(false);
        binding.lineChart.setDrawGridBackground(false);
        binding.lineChart.setScaleEnabled(false);//不缩放
        binding.lineChart.getAxisRight().setEnabled(false);
        binding.lineChart.setExtraOffsets(0, 00, 0, 0);
//        MyMarkerView myMarkerView = new MyMarkerView(getActivity(), R.layout.layout_chart_marker_view);
//        myMarkerView.setChartView(binding.lineChart);
//        binding.lineChart.setMarker(myMarkerView);

        Legend l = binding.lineChart.getLegend();
        l.setVerticalAlignment(Legend.LegendVerticalAlignment.BOTTOM);
        l.setHorizontalAlignment(Legend.LegendHorizontalAlignment.LEFT);
        l.setOrientation(Legend.LegendOrientation.HORIZONTAL);
        l.setDrawInside(false);
        l.setEnabled(false);


        int XLabelCount = 5;
        if (taskNumBeans.size() % 2 == 0) {
            XLabelCount = 6;
        }

        XAxis xAxis = binding.lineChart.getXAxis();
        xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
        xAxis.setLabelCount(XLabelCount);
        xAxis.setDrawGridLines(true);
        xAxis.setDrawAxisLine(false);
        xAxis.setAxisMinimum(0);
        xAxis.setGranularity(1f);
        xAxis.setGridColor(getResources().getColor(R.color.bg_color_c1c));
        xAxis.setTextColor(getResources().getColor(R.color.text_color999));

        xAxis.setValueFormatter(new ValueFormatter() {
            @Override
            public String getFormattedValue(float value) {
                int MyValue = (int) value;
                if (value < 0 || MyValue > taskNumBeans.size() - 1) {
                    return "";
                }

                String[] data = taskNumBeans.get(MyValue).getRq().split("-");
                return data[1];


            }
        });

        List<Integer> numList = new ArrayList<>();

        for (int i = 0; i < taskNumBeans.size(); i++) {
            int num = taskNumBeans.get(i).getNum();
            numList.add(num);
        }

        int YLabelCount = 5;
        if (Collections.max(numList) % 2 == 0) {
            //偶数的时候 设置为6  奇数的时候设置为5
            YLabelCount = 6;
        }

        YAxis leftAxis = binding.lineChart.getAxisLeft();
        leftAxis.setLabelCount(YLabelCount, false);
        leftAxis.setAxisMinimum(0); // this replaces setStartAtZero(true)
        leftAxis.setGranularity(1f);
        leftAxis.setGridColor(getResources().getColor(R.color.bg_color_c1c));
        leftAxis.setTextColor(getResources().getColor(R.color.text_color999));


        YAxis rightAxis = binding.lineChart.getAxisRight();
//        rightAxis.setTypeface(mTf);
        rightAxis.setLabelCount(YLabelCount, false);
        rightAxis.setDrawGridLines(false);
        rightAxis.setAxisMinimum(0); // this replaces setStartAtZero(true)
        rightAxis.setGranularity(1f);
        rightAxis.setGridColor(getResources().getColor(R.color.bg_color_c1c));
        rightAxis.setTextColor(getResources().getColor(R.color.text_color999));


        // set data
        binding.lineChart.setData((LineData) generateDataLine(taskNumBeans));

        // do not forget to refresh the chart
        binding.lineChart.invalidate();
        binding.lineChart.animateX(750);

    }

    private LineData generateDataLine(List<ReportTrendBean.EventNumBean> taskNumBeans) {


        ArrayList<Entry> e1 = new ArrayList<Entry>();

        for (int i = 0; i < taskNumBeans.size(); i++) {
            int num = taskNumBeans.get(i).getNum(); //顾客数

            e1.add(new Entry(i, num));

        }

        LineDataSet d1 = new LineDataSet(e1, "New DataSet " + ", (1)");

        d1.setLineWidth(2f);
        d1.setCircleRadius(6f);
        d1.setCircleHoleRadius(3f);
        d1.setDrawCircleHole(true);
        d1.setCircleColor(Color.argb(76, 153, 211, 163));
        d1.setCircleHoleColor(Color.rgb(78, 171, 94));
        d1.setHighLightColor(Color.rgb(153, 211, 163));
        d1.setColor(Color.rgb(153, 211, 163));
        d1.setDrawValues(false);
        d1.setMode(LineDataSet.Mode.CUBIC_BEZIER);


        ArrayList<ILineDataSet> sets = new ArrayList<ILineDataSet>();
        sets.add(d1);
        LineData cd = new LineData(sets);
        return cd;
    }

    /**
     * 刷新数据
     */
    public void refresh() {
        getReportToatal();
        getReportTag();
        getReportTrend();
    }

}